<!--
 * @Author: Badcandy 568197314@qq.com
 * @Date: 2023-01-10 20:31:35
 * @LastEditors: Badcandy 568197314@qq.com
 * @LastEditTime: 2023-01-12 22:53:41
 * @FilePath: \dcollege\src\views\note\noteEditor\noteEditor.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by Badcandy 568197314@qq.com, All Rights Reserved. 
-->
<template>
  <div class="editor-bg">
    <var-app-bar
      title="笔记本"
      title-position="center"
      text-color="#000"
      color="white"
      :elevation="false"
    >
      <template #left>
        <var-button @click="goBack" color="#fff" text-color="#000" round text>
          <var-icon name="chevron-left" :size="24" />
        </var-button>
      </template>
      <template #right>
        <var-button>完成</var-button>
      </template>
    </var-app-bar>
    <!-- 工具栏 -->
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <!-- 编辑器 -->
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
    <!-- 最后编辑日期 -->
    <div class="editor-date">
      <span>{{ date }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

const route = useRoute();

const title = `${route.query.title}` || null;
const content = `${route.query.content}` || null;
const date = `${route.query.date}` || null;

const router = useRouter();
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("");

const mode = "default";

function goBack() {
  router.go(-1);
}
// 模拟 ajax 异步获取内容
onMounted(() => {
  // setTimeout(() => {
  //     valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
  // }, 1500)
});

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  if (!title) {
    valueHtml.value = "";
  } else {
    valueHtml.value = `<h1>${title}</h1><br><p>${content}</p>`;
  }
};
</script>

<style lang="less" scoped>
.editor-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  background: #fff;
}
.editor-date {
  display: flex;
  padding-left: 0.625rem;
  font-size: 0.85rem;
  color: rgb(213, 213, 213);
}
</style>